/*
###############################################################################################
#                                                                                             # 
# The Page is used by the Site Users who want to Register with the Site.This Page             #
# contains all the General Information about the User. This Page is  created at               #
# the root folder.                                                                            #
#                                                                                             #
#     Author : Jaspal Mehta                                                                   #
#     Dated  : 23-Feb-2006                                                                    #
#                                                                                             #
###############################################################################################
*/

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using SiteManager;

public partial class patient_registration : System.Web.UI.Page
{
    //Create an Object of Manager defined in the Namespace
    Manager manager = new Manager(true,"ConnectionString");
    private int UserID;
    Patient obj = new Patient();
    string offer = "";
    string sgender = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.keywordsContent = "find a doctor, ask a doctor, search doctor, doctor list, doctors online, patient registration, best doctors, top doctors";
        Master.descriptionContent = "Findadoc.com offers patient registration for person looking best doctors. Find a doctor, specialized doctor from types of doctors, best doctor list online to end up your search for top doctors of various categories by our best doctor list.";
        Master.titleContent = "Register To Find A Doctor, Ask A Doctor From Best Doctors Online, Doctor List";
        Master.TopLoginIMG = true;
        //if (Session["userID"] != null && Session["userID"].ToString().Trim() != "")
        //{
        //    UserID = Convert.ToInt32(Session["userID"]);
        //    GetUserInfoByUserId();
        //}
       // errorlist.Text = "";
        trError.Visible = false;
        if (!IsPostBack)
        {
            //if (Request.QueryString["id"] != null)
            //{ UserID = Convert.ToInt32(Request.QueryString["id"].ToString()); }

            //Function called to fill the country names in the combo box
            fillselcountry();

            //Function called to fill the Security Questions listed
            fillsecurityques();

            //Function called to fill the Health Plan Listed
            fillhealthcplan();

            fillBirthYearDdl();
            //ADD DoctorType CHECK AT 16/02/2008 BY RANJEET
            if (Session["userID"] != null && Session["userID"].ToString().Trim() != "" && Session["DoctorType"].ToString() == "User")
            {
                UserID = Convert.ToInt32(Session["userID"]);
                GetUserInfoByUserId();

            }

            

        }
        
 
    }

    /// <summary>
    /// Function  to fill the country names in the combo box
    /// </summary>
    public void fillselcountry()
    {
        manager.BindList("select countrycode,countryname from tbl_country order by countryname", "countryname", "countrycode", combocountry, "select");
        //manager.BindList("select countrycode,countryname from tbl_country where countrycode<>'us' order by countryname", "countryname", "countrycode", combocountry, "select");
        //ListItem li= new ListItem("United States of America","US");
        //combocountry.Items.Insert(1, li);
    }

    /// <summary>
    ///  fill the Security Questions listed
    /// </summary>
    public void fillsecurityques()
    {
        manager.BindList("select secquestion,sno from tbl_secquestions" , "secquestion","sno", combosecquestion, "select");
    }

    /// <summary>
    ///  fill the Health Plan Listed
    /// </summary>
    public void fillhealthcplan()
    {
        //manager.BindList("select healthcplan,sno from tbl_healthcplan", "healthcplan", "sno", combohplan, "select");
        manager.BindList("select id,name from tbl_InsuranceCompanies order by name", "Name", "Id", combohplan, "select");
    }

    private void fillBirthYearDdl()
    {
        for (int i = (DateTime.Today.Year - 6); i > 1910; i--)
            ddlBirthYear.Items.Add(new ListItem(i.ToString(),i.ToString()));
        ddlBirthYear.Items.Insert(0, new ListItem("--Select--",""));
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
     
        //check the Javascript validation that all the Fields in the Form are properly filled
       // This is checked if Javascript is disabled in the Browser.
        
        Validation validateForm = new Validation();
        validateForm.AddValidation(txtemailid.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Email-Id", "");
        validateForm.AddValidation(txtpassword.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Password", "");
        validateForm.AddValidation(txtpassword.Text.Trim(), Validation.ValidationCommand.minlen, "Please enter atleast 6 characters in password", "6");  
        validateForm.AddValidation(txtrepassword.Text.Trim(), Validation.ValidationCommand.required, "Please Retype Your Password", "");
        validateForm.AddValidation(combosecquestion.Text.Trim(), Validation.ValidationCommand.notequal, "Please Select Security Question", "0");
        validateForm.AddValidation(txtsecanswer.Text.Trim(), Validation.ValidationCommand.required, "Please Enter your Secret Answer", "");
        validateForm.AddValidation(txtnickname.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Your Nick Name", "");
        validateForm.AddValidation(txtfname.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Your First Name", "");
        validateForm.AddValidation(txtlname.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Your last name", "");
        validateForm.AddValidation(txtrepassword.Text.Trim(), Validation.ValidationCommand.equal, "Your confirm Password not match",txtpassword.Text.Trim());
        
        //Change 04/24/2006 - Birth date changed to birth year
        //validateForm.AddValidation(txtbirthdate.Text.Trim(), Validation.ValidationCommand.required, "Please Select Your Birth Date", "");
        validateForm.AddValidation(ddlBirthYear.Text.Trim(), Validation.ValidationCommand.required, "Please Select Your Birth Year", "");
        //End Change 04.24.2006

        //Change 04/24/2006 - Address, city not mandatory
        //validateForm.AddValidation(txtaddress1.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Address1", "");
        //validateForm.AddValidation(txtcity.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Your City", "");
        //End Change

        validateForm.AddValidation(txtzipcode.Text.Trim(), Validation.ValidationCommand.required, "Please Enter your Zip Code", "");
        validateForm.AddValidation(txtstate.Text.Trim(), Validation.ValidationCommand.required, "Please Enter Your State", "");
        validateForm.AddValidation(combocountry.Text.Trim(), Validation.ValidationCommand.required, "Please Select Your Country", "");
        
        //Change 04/24/2006 - Healthplan not mandatory
        //validateForm.AddValidation(combohplan.Text.Trim(), Validation.ValidationCommand.required, "Please Select Your Health Care Plan", "");
        //End Change 04/24/2006

        validateForm.AddValidation(txtaddress1.Text.Trim(), Validation.ValidationCommand.maxlen, "Address Maximum Length is Only 100 Characters", "99");
        validateForm.AddValidation(txtaddress2.Text.Trim(), Validation.ValidationCommand.maxlen, "Address Maximum Length is Only 100 Characters", "99");
        validateForm.AddValidation(txtcity.Text.Trim(), Validation.ValidationCommand.alphabetic, "Please enter Correct City Name.", "");
        validateForm.AddValidation(txtstate.Text.Trim(), Validation.ValidationCommand.alphabetic, "Please enter Correct State Name.", "");
        validateForm.AddValidation(txtemailid.Text.Trim(), Validation.ValidationCommand.email, "Please Enter Correct Email", "");
        ArrayList arr = validateForm.ErrList;
       
        if (!validateForm.CheckError() || !captcha.IsValid)
        {
            if (!captcha.IsValid)
            {
                arr.Insert(arr.Count, captcha.ErrorMessage);
            }
            trError.Visible = true;
            errorlist.DataSource = arr;
            errorlist.DataBind();
            return;
        }
        else 
        {
            trError.Visible = false; 
        }

        // start checking for duplicate email when inserting a new record                  
        string sql = "";

        //int id = (int)ViewState["id"];

        //if (id == 0)
            sql = "select count(*) from tbl_Users where Email='" + txtemailid.Text + "' and  isDelete=0 ";
        //else
        //{
           // sql = "select count(*) from tbl_Users where Email='" + txtemail.Text + "' and id<>" + id + " and  isDelete=0 ";
        //}

            if (Session["userID"].ToString() == "")
            {
                if (errorlist.Text == "")
                {
                    DataSet dsEmail = manager.ExecuteQuery(sql, "tbl1");

                    if (dsEmail.Tables[0].Rows.Count > 0)
                    {
                        //if (Request.QueryString["id"] == "0")
                        //{
                        if (Convert.ToInt32(dsEmail.Tables[0].Rows[0][0].ToString()) > 0)
                        {
                            trError.Visible = true;
                            //errorlist.Visible = true;                        
                            errorlist.ForeColor = System.Drawing.Color.Red;
                            errorlist.Items.Add("Email already exists!! Please try with a different email id.");
                            return;
                        }
                        //}
                    }
                }
                // end checking for duplicate email 
                string temail = txtemailid.Text.Replace("'", "''").Trim();
                string tfname = txtfname.Text.Replace("'", "''").Trim();
                string tmname = txtmname.Text.Replace("'", "''").Trim();
                string tlname = txtlname.Text.Replace("'", "''").Trim();
                string tpswd = txtpassword.Text.Replace("'", "''").Trim();
                string tsecques = combosecquestion.SelectedItem.Value.ToString().Trim();
                string tsecans = txtsecanswer.Text.Replace("'", "''").Trim();
                string nicknm = txtnickname.Text.Replace("'", "''").Trim();
                //string tbdate = txtbirthdate.Text.Replace("'", "''").Trim();
                string taddr1 = txtaddress1.Text.Replace("'", "''").Trim();
                string taddr2 = txtaddress2.Text.Replace("'", "''").Trim();
                string tcity = txtcity.Text.Replace("'", "''").Trim();
                string tzipcode = txtzipcode.Text.Replace("'", "''").Trim();
                string tstate = txtstate.Text.Replace("'", "''").Trim();
                string tcountry = combocountry.SelectedItem.Value.ToString().Trim();
                string bdate = txtbirthdate.Text.Replace("'", "''").Trim();
                string birthYear = ddlBirthYear.SelectedValue.ToString().Trim();
                // string gender = combogender.SelectedItem.Value.ToString().Trim();
                string hcplan = combohplan.Text.Replace("'", "''").Trim();
                //string offer=CheckBox1.Text.Replace

                if (chkoffer.Checked)
                {
                    offer = "1";
                }

                if (rad_gender.Checked)
                {
                    sgender = "M";
                }
                if (rad_gender1.Checked)
                {
                    sgender = "F";
                }


                DateTime tregdt = DateTime.Now;

                string sqlQuery = "";

                //Insert Site User Query
                sqlQuery = "insert into tbl_Users(fName,MName,LName,";
                sqlQuery += "Email,Password,Address1,Address2,City,ZipCode,State,CountryId";
                sqlQuery += ",RegDate,BirthDate,BirthYear,HealthCPlan,Securityques,SecurityAns,NickName,freeoffer,Gender)values('";
                sqlQuery += tfname + "','" + tmname + "','" + tlname + "','" + temail + "','" + tpswd + "','" + taddr1 + "','" + taddr2 + "','" + tcity + "','" + tzipcode + "','" + tstate + "','" + tcountry + "','" + tregdt + "','" + bdate + "','" + birthYear + "','" + hcplan + "','" + tsecques + "','" + tsecans + "','" + nicknm + "','" + offer + "','" + sgender + "')";
                //  ViewState["vsEmail"] = temail;
                //errorlist.Text = "";
                //errorlist.Visible = true;
                //errorlist.Text = "You are Registered Successfully !!";

                try
                {
                    manager.ExecuteQuery(sqlQuery);
                    //If Query is successfull the User will be redirected to the main page
                    //Place the name of the file here, where the user has to be redirected.
                    Response.Redirect("../success.aspx?ref=patient");
                }
                // If any Exception occurs like if a System throws any exception at the 
                // time of running a query than it will be caught by the Mother class of 
                // Exception i.e 'Throwable'for which object has been created with a name of 'es'.
                catch (Exception es)
                {
                    Response.Write(es.ToString());
                }
            }
                if (!Session["userID"].ToString().Equals(0))
            {
                //if (!ViewState["vsEmail"].ToString().Equals(0))
                //{
                    //obj.PatientId = Convert.ToInt32(ViewState["PId"]);
                    obj.PatientId = Convert.ToInt32(Session["userID"]);
                    obj.FirstName = txtfname.Text.ToString().Trim();
                    obj.MiddleName = txtmname.Text.ToString().Trim();
                    obj.LastName = txtlname.Text.ToString().Trim();
                    //if (!ViewState["vsEmail"].ToString().Equals(0))
                    obj.Password = txtpassword.Text.ToString().Trim();
                    obj.Address1 = txtaddress1.Text.ToString().Trim();
                    obj.Address2 = txtaddress2.Text.ToString().Trim();
                    obj.City = txtcity.Text.ToString().Trim();
                    obj.State = txtstate.Text.ToString().Trim();
                    obj.ZipCode = txtzipcode.Text.ToString().Trim();
                    obj.Country = combocountry.SelectedItem.Value.ToString().Trim();
                    obj.RegDate = System.DateTime.Now.ToString();
                    obj.BirthDate = txtbirthdate.Text.Replace("'", "''").Trim();
                    obj.BirthYear = ddlBirthYear.SelectedValue.ToString().Trim();
                    obj.HealthCPlan = combohplan.Text.Replace("'", "''").Trim();
                    obj.SecurityQues = combosecquestion.SelectedItem.Value.ToString().Trim();
                    obj.SecurityAns = txtsecanswer.Text.Replace("'", "''").Trim();
                    obj.NickName = txtnickname.Text.Replace("'", "''").Trim();
                    obj.FreeOffer = offer;
                    obj.Gender = sgender;
                    obj.UpdateUserInfo();
                    Response.Redirect(Session["strHttp"].ToString() + "User/UserContent.aspx");
                    
                //}


            }
    }  
    protected void ImageButton2_Click(object sender, EventArgs e)
    {
        Response.Redirect("../default.aspx");        
    }
    private void GetUserInfoByUserId()
    {
        
        if (rad_gender.Checked)
        {
            sgender = "M";
        }
        if (rad_gender1.Checked)
        {
            sgender = "F";
        }
        obj.PatientId = UserID;
        DataSet tmpds = obj.FillUserInfoByUserID();
        //ViewState["PId"] = UserID;
        txtfname.Text = tmpds.Tables[0].Rows[0]["fName"].ToString();
        txtmname.Text = tmpds.Tables[0].Rows[0]["MName"].ToString();
        txtlname.Text = tmpds.Tables[0].Rows[0]["LName"].ToString();
        txtbirthdate.Text = tmpds.Tables[0].Rows[0]["BirthDate"].ToString();
        txtemailid.Text = tmpds.Tables[0].Rows[0]["Email"].ToString();
        ddlBirthYear.Text = tmpds.Tables[0].Rows[0]["BirthYear"].ToString(); 
        txtemailid.ReadOnly = true;
        txtpassword.Text = tmpds.Tables[0].Rows[0]["Password"].ToString();
        if (tmpds.Tables[0].Rows[0]["Gender"].ToString() == "M")
        {
            rad_gender.Checked = true;
        }
        else if (tmpds.Tables[0].Rows[0]["Gender"].ToString() == "F")
        {
            rad_gender1.Checked = true;
        }
        txtaddress1.Text = tmpds.Tables[0].Rows[0]["Address1"].ToString();
        txtaddress2.Text = tmpds.Tables[0].Rows[0]["Address2"].ToString();
        txtcity.Text = tmpds.Tables[0].Rows[0]["City"].ToString();
        txtzipcode.Text = tmpds.Tables[0].Rows[0]["ZipCode"].ToString();
        txtstate.Text = tmpds.Tables[0].Rows[0]["State"].ToString();
        combocountry.Text = tmpds.Tables[0].Rows[0]["Countryid"].ToString();
        txtsecanswer.Text = tmpds.Tables[0].Rows[0]["SecurityAns"].ToString();
        combosecquestion.Text= tmpds.Tables[0].Rows[0]["SecurityQues"].ToString();
        txtnickname.Text = tmpds.Tables[0].Rows[0]["NickName"].ToString();
        combohplan.Text = tmpds.Tables[0].Rows[0]["HealthCPlan"].ToString();
        if (tmpds.Tables[0].Rows[0]["FreeOffer"].ToString() == "1")
        {
            chkoffer.Checked = true;
        }
        else
        {
            chkoffer.Checked = false;
        }
       
        

    }
    
    
}
